<template>
  <div>
    <el-form-item
      label="上传附件"
      class="small"
      id="uploadid"
    >
    <span class="" slot="label">
      <span class="item-label">上传附件</span>
       <el-tooltip content="附件支持上传图片，最多可上传5张" placement="top">
        <button class="circleButton" type="button">?</button>
      </el-tooltip><i class="item-label">：</i>
    </span>
      <div class="file-wrapper" >
        <div class="file-list flex-wrap">
          <div class="file-item" v-for="(item,index) in files" :key="item.uid">
            <img :src="item.url" v-if="item.fileType === 'image'" alt="">
            <video :src="item.url" v-if="item.fileType === 'video'"></video>
            <div class="file-bg" v-if="item.fileType === 'file'">
              <span class="iconfont icon-pc-wenjianzhanwei file-icon"></span>
              <span class="file-title">{{item.name}}</span>
            </div>
            <div class="mark">
              <i class="el-icon-zoom-in" @click="clickFile(item)"></i>
              <i class="el-icon-delete" @click="removeFile(item,index)"></i>
            </div>
          </div>

        </div>
        <div id="upload_img">
          <el-upload
            ref="upload_img"
            name="file"
            :action="uploadConfig.url"
            :before-upload="beforeUpload"
            :file-list="files"
            :on-success="handleSuccess"
            @change="changeFileList"
            :limit="limit"
            :accept="acceptTypes"
            multiple
            :headers="uploadConfig.headers"
          >
            <i class="el-icon-plus icon"></i>
          </el-upload>
        </div>

      </div>
      <span v-if="error" class="el-form-item__error error-label">附件不能为空。</span>
    </el-form-item>
    <el-dialog
      v-if="videoAndImgList[this.selectFileIndex]?.url"
      :visible.sync="previewFileVisible"
      class="preview-file-dialog">
      <div class="el-dialog__close el-icon el-icon-close closeVideoBtn" @click="closeImgRepeat"></div>
       <EasyPlayer ref="videoPlayer"
                  :videoUrl="videoAndImgList[selectFileIndex].url"
                  :easyStretch="false"
                  :autoplay="false"
                  alt="未上传视频"
                  :live="false"
                  :show-custom-button="true"
                  style="width: 100%;aspect-ratio: 16 / 9"
                  v-if="videoAndImgList[selectFileIndex].url.indexOf('.mp4') !== -1 || videoAndImgList[selectFileIndex].url.indexOf('.MP4') !== -1"
                  :has-audio="$store.getters.flvHasAudio || !videoAndImgList[selectFileIndex].url.includes('.flv')">
      </EasyPlayer>
      <img :src="videoAndImgList[selectFileIndex].url" alt="图片" v-else style="max-width: 100%;max-height: 100%">

      <div class="prevLeft" @click="prevUrl(0)">
        <i class="el-icon-arrow-left"></i>
      </div>
      <div class="nextRight" @click="prevUrl(1)">
        <i class="el-icon-arrow-right"></i>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import {getToken, previewFile} from "@/utils/common";

export default {
  name: "uploadFile.vue",
  data(){
    return {
      limit: 9, // 限制上传文件数量，根据需要修改
      acceptTypes: 'image/png,image/jpg,image/jpeg,video/mp4,.txt,.doc,.docx,.pdf,.ppt,.pptx,.xlsx', // 允许上传的文件类型
      fileNameMap:['png','jpg','jpeg','mp4','txt','doc','docx','pdf','ppt','pptx','xlsx'],
      files:[],
      uploadConfig:{
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/file/base/common/upload',
      },
      rules:{
        files: [
          { validator: this.judgeFile, trigger: ['change','blur'] }
        ],
      },
      error:false,
      videoAndImgList:[],
      previewFileVisible:false,
      selectFileIndex:0
    }
  },
  watch:{
    files:{
      handler(val) {
        this.$emit('update:fileList',val);
      },
      deep:true
    }
  },
  prop:{
    fileList:{
      type:Array,
      default:()=>[]
    }
  },
  computed:{
  },
  methods:{
    disableContextmenu(){
      return false
    },
    // 上传校验
    beforeUpload(file) {
      const size = file.size / 1024 / 1024 < 10
      const fileName = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase();
      let flag = true;
      if(!this.fileNameMap.includes(fileName)) {
        flag = false;
        this.$message.error("支持上传格式为txt、doc、docx、pdf、ppt、pptx、xlsx格式。")
      }
      if (!size) {
        flag = false
        this.$message.error('上传文件大小不能超过 10MB。')
      }
      return flag
    },
    changeFileList(){
      this.error = !this.files.length;
    },
    // 添加文件
    handleSuccess(res){
      console.log(res,"res")
      const fileMap = {
        image:1,
        video:2,
        file:3
      }
      if(res.code === 200) {
        const type = this.judgeFileType(res.data.fileSuffix);
        this.files.push({
          id:res.data.fileId,
          name:res.data.fileName,
          url:res.data.fileUrl,
          suffix:res.data.fileSuffix,
          fileType:type,
          type:fileMap[type]
        })
        this.videoAndImgList = this.files.filter(item=>item.fileType === 'video' || item.fileType === 'image')
      }
      console.log(this.files,"files")
    },
    judgeFileType(suffix) {
      const fileSuffix = suffix.toLowerCase();
      const imageMap = ['.jpeg','.jpg','.png'];
      const fileMap = ['.pptx','.pdf','.docx','.xlsx','.txt'];
      const videoMap = ['.mp4'];
      if(imageMap.includes(fileSuffix)) {
        return 'image';
      }
      if(fileMap.includes(fileSuffix)) {
        return 'file';
      }
      if(videoMap.includes(fileSuffix)) {
        return 'video'
      }
    },
    removeFile(item,index) {
      this.files.splice(index,1);
    },
    clickFile(item) {
      if(item.fileType === 'file') {
        const url = location.origin + '/previewFile?url=' + encodeURIComponent(item.url);
        window.open(url)
      }else {
        const index = this.videoAndImgList.findIndex(file=>file.url === item.url);
        this.handlePreview(item,index)
      }

    },
    checkFiles(){
      this.error = !this.files.length;
      return !!this.files.length;
    },
    /**
     * 预览
     */
    handlePreview(file,index) {
      this.selectFileIndex = index;
      this.previewFileVisible = true;
    },
    /**
     * 关闭预览弹窗
     */
    closeImgRepeat() {
      this.previewFileVisible = false;
    },
    /**
     * 图片或视频附件上下一张预览
     */
    prevUrl(type) {
      if(type === 1) {
        this.selectFileIndex = this.selectFileIndex === this.files.length -1 ? 0 : this.selectFileIndex + 1;
      }else {
        this.selectFileIndex = this.selectFileIndex === 0 ? this.files.length : this.selectFileIndex = this.selectFileIndex - 1;
      }
    },
  }
}
</script>

<style lang="scss" scoped>
#uploadid {
  .item-label {
    font-weight: 600;
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
  }
  .icon {
    font-size: 12px;
    color: #909399;
    line-height: 70px;
    font-weight: bold;
  }
  .file-wrapper {
    display: flex;
    flex-direction: row;
    flex-wrap:wrap;
  }
  .flex-wrap {
    display:flex;
    flex-wrap:wrap;
  }
  .img-size {
    height:55px;
    width:93px;
  }
  .circleButton {
    height: 16px;
    width: 16px;
    border-radius: 50%;
    background-color: orange;
    color: white;
    font-size: 12px
  }
  #upload_img {
    width: 70px;
    height: 70px;
    background: #F5F7FA;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
    overflow: hidden;
    text-align: center;
    .el-upload-list {
      display: none;
    }
  }
  .file-item {
    width: 70px;
    height: 70px;
    background: #F5F7FA;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
    overflow: hidden;
    margin:0 12px 12px 0;
    position: relative;
    img {
      width: 100%;
      height: 100%;
      display: block;
      object-fit: contain;
    }
    video {
      width: 100%;
      height: 100%;
    }
    .mark {
      background: rgba(0,0,0,.5);
      transition: all .3s;
      opacity: 0;
      position: absolute;
      inset: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      i {
        font-size: 20px;
        color: #fff;
        cursor: pointer;
      }
      .el-icon-zoom-in {
        &::before {
          font-family: iconfont !important;
          content: "\E621";
        }
        margin-right: 12px;
      }
      &:hover {
        opacity: 1;
      }
    }
  }
  .error-label {
    position: absolute;
    left: 4px;
    bottom: 0;
  }
  .file-bg {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    width: 100%;
    position: relative;
    .file-icon {
      font-size: 30px;
      color: #1890FF;
    }
    .file-title {
      width: 100%;
      position: absolute;
      bottom: 0;
      left: 0;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      height: 20px;
      line-height: 20px;
    }
  }
}
.preImg /deep/ .el-dialog {
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  border: none;
  box-shadow: none;
}

.preImg /deep/ .el-dialog .el-dialog__body {
  padding: 0;
  overflow-y: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.preImg /deep/ .el-dialog .el-dialog__header {
  display: none;
}

.closeVideoBtn {
  width: 46px;
  height: 46px;
  line-height: 46px;
  position: fixed;
  top: 30px;
  right: 30px;
  transform: translate(-50%, -50%);
  z-index: 2;
  font-size: 26px;
  color: #FFFFFF;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.52) !important;
  cursor: pointer;
  text-align: center;
}

.video-player {
  height: 100%;
  width: 100%;
}

.video-player /deep/ .video-js.vjs-fluid {
  width: 100%;
  height: 100%;
  padding: 0;
}

.prevLeft {
  width: 61px;
  height: 61px;
  background: rgba(0, 0, 0, 0.52);
  border-radius: 50%;
  position: fixed;
  left: 45px;
  color: #FFFFFF;
  text-align: center;
  line-height: 64px;
  font-size: 32px;
}

.nextRight {
  width: 61px;
  height: 61px;
  background: rgba(0, 0, 0, 0.52);
  border-radius: 50%;
  position: fixed;
  right: 45px;
  color: #FFFFFF;
  text-align: center;
  line-height: 64px;
  font-size: 32px;
}

</style>
<style lang="scss">
.preview-file-dialog {
  .easy-player .easy-big-play-button {
    opacity: 0;
  }
  .el-dialog__headerbtn {
    top: 8px;
  }
  .el-dialog {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    border: none;
    box-shadow: none;
  }

  .el-dialog .el-dialog__body {
    padding: 0;
    overflow-y: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .el-dialog .el-dialog__header {
    display: none;
  }
}
</style>
